import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import BookView from '@/views/BookView.vue';
import ClassifyView from '@/views/ClassifyView.vue';
import AdminView from '@/views/AdminView.vue';
import IndexView from '@/views/IndexView.vue';
import LoginView from '@/views/LoginView.vue';
import UserView from '@/views/UserView.vue';
import accountApi from '@/api/accountApi';
import { useTokenStore } from '@/stores/token';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/user',
      name: 'user',
      component: UserView
    }, {
      path: '/login',
      name: 'login',
      component: LoginView
    }, {
      path: '/',
      name: 'home',
      component: HomeView,
      redirect: '/login',
      children: [ //子路由 访问子路由，父路由也会渲染
        {
          path: '/admin',
          component: AdminView
        },
        {
          path: '/book',
          component: BookView
        },
        {
          path: '/classify',
          component: ClassifyView
        },
        {
          path: '/index',
          component: IndexView
        }
      ]
    }
  ]
});

//导航守卫
router.beforeEach((to , from) => {
  if(to.path == '/login'){
    return true;
  }else {
    const tokenStore = useTokenStore();
    if (!tokenStore.tokenStr){
      return "/login";
    }else {
      return true;
    }
  }
});

export default router
